package com.right.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Tools.PageData;
import com.commons.AjaxResponse;
import com.google.gson.Gson;
import com.right.dao.UsersDao;
import com.right.dao.impl.UsersDaoImpl;
import com.right.entity.Users;
import com.right.service.UserService;
import com.right.service.impl.UserServiceImpl;

/**
 * Servlet implementation class UserServlet
 */

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       UsersDao usersDao = new UsersDaoImpl();
       UserService userService = new UserServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String op = "";
		if (request.getParameter("op")!=null) {
			op = request.getParameter("op");
		}
		if ("add".equals(op)) {
			doRegister(request, response);
		}else if ("delete".equals(op)) {
			doDelete(request, response);
		}else if ("update".equals(op)) {
			doUpdate(request, response);
		}else if ("selectByPage".equals(op)) {
			doSelByPage(request, response);
		}else if ("login".equals(op)) {
			doLogin(request, response);
		}else if ("".equals(op)) {
			response.sendRedirect("main.jsp");
		}
	
	}
	
	public void doUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 int userid=0;
	     if (request.getParameter("userid")!=null) {
			userid =Integer.parseInt(request.getParameter("userid"));
		}       
	     System.out.println(userid);
		  String  username  =request.getParameter("username");
		  String  usersex  =request.getParameter("usersex");
		  String  address   =request.getParameter("address");
		  String  usercall   =request.getParameter("usercall");
		  double  money =Double.parseDouble(request.getParameter("money"));
		  int   point  =Integer.parseInt(request.getParameter("point"));   
		  Users users=new Users(userid, username, usersex, address, usercall, money, point);

	             boolean flag=usersDao.updateusers(users);  
	             System.out.println(flag);
	             AjaxResponse res = new AjaxResponse(flag+"", 200);
	 		    //3将list转为json格式的字符串
	 		    Gson gson=new Gson();
	 		    String jsonString=gson.toJson(res); 
	 		    //4 响应
	 		    PrintWriter outPrintWriter=response.getWriter();
	 		    outPrintWriter.print(jsonString);
	 		    //关闭
	 		    outPrintWriter.close();
	}
	
	public void doDelete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		     int userid=0;
		     if (request.getParameter("userid")!=null) {
				userid =Integer.parseInt(request.getParameter("userid"));
			}
		     //2调用 service的方法
		    boolean flag=userService.delusers(userid);
		    AjaxResponse res = new AjaxResponse(flag+"", 200);
		    //3将list转为json格式的字符串
		    Gson gson=new Gson();
		    String jsonString=gson.toJson(res); 
		    //4 响应
		    PrintWriter outPrintWriter=response.getWriter();
		    outPrintWriter.print(jsonString);
		    //关闭
		    outPrintWriter.close();
		    
	}
	
	/**
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void doRegister(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String userpwd = request.getParameter("userpwd");
		String usersex = request.getParameter("usersex");
		String address = request.getParameter("address");
		String usercall = request.getParameter("usercall");
		System.out.println(username+userpwd+usersex+address+usercall);
		Users users = new Users(0, username, userpwd, usersex, address, usercall, 0, 0);
		boolean flag = userService.addusers(users);
		if (flag) {
			request.getSession().setAttribute("username", username);
			request.getRequestDispatcher("userlogin.jsp").forward(request, response);
		}else {
			request.setAttribute("msg", "注册失败");
			request.getRequestDispatcher("userregister.jsp").forward(request, response);
		}
	}

	/**
	 * 登录方法
	 * username用户名
	 * userpwd用户密码
	 * userService服务层方法
	 */
	public void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String userpwd = request.getParameter("userpwd");
		if (userService.login(username, userpwd)) {
			request.getSession().setAttribute("username", username);
			//用户选择了记住密码
			if(request.getParameter("remember")!=null) {
				//创建cookie，并设置其过期时间，存储到本地
				Cookie cookie1 = new Cookie("username", username);
				cookie1.setMaxAge(60*60);//过期时间1h
				Cookie cookie2 = new Cookie("userpwd", userpwd);
				cookie2.setMaxAge(60*60);
				//将cookie的信息存储在本地: addCookie
				response.addCookie(cookie1);
				response.addCookie(cookie2);
			}
			//通过用户名查询用户id
			int userid = userService.getIdByName(username).getUserid();
			Users users = userService.getUserByid(userid);
//			System.out.println(userid);
//			//将用户id记录在session中
			HttpSession session = request.getSession();
			session.setAttribute("users", users);
			request.getRequestDispatcher("main.jsp").forward(request, response);
		}else {
			request.setAttribute("msg", "输入信息有误，请检查用户名或密码是否正确");
			request.getRequestDispatcher("userlogin.jsp").forward(request, response);
		}
	}

	/**
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void doSelByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//接受jsp传递过来的值（keywords,page,pageSize）
		String keywords = "";
		int page = 1;
		int pageSize = 7;
		if (request.getParameter("keywords")!=null) {
			keywords = request.getParameter("keywords");
			
		}if (request.getParameter("page")!=null) {
			page = Integer.parseInt(request.getParameter("page"));
		}if (request.getParameter("pageSize")!=null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		
		PageData<Users> pd = userService.getUserByPage(page, pageSize, keywords);
		//传PageData到jsp页面
		request.setAttribute("pd", pd);
		request.setAttribute("keywords",keywords);
		//转发(地址未定)
		request.getRequestDispatcher("adminuser.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
